

#include "lib/type.h"
#include "sim_timer_config.h"

#define count_offset        0
#define timeout_offset      1
#define running_offset      2
#define overtime_offset     3

static volatile uint16_t SIM_TIMERS[SIM_TIMER_MAX*4];

void sim_timer_init(void)
{
    uint8_t i;
    for (i = 0; i < SIM_TIMER_MAX*4; i++) {
        SIM_TIMERS[i] = 0;
    }
}

void sim_timer_tick_hander(void)
{
	uint8_t i;
    uint8_t j;
    for (i = 0; i < SIM_TIMER_MAX; i++) {
        j = i*4;
        if ((SIM_TIMERS[j+running_offset] == 1)&&(SIM_TIMERS[j+overtime_offset] == 0)) {
            if(SIM_TIMERS[j+count_offset] > 0){
                SIM_TIMERS[j+count_offset]--;
            }
            else{
                SIM_TIMERS[j+count_offset] = 0;
            }
            if (SIM_TIMERS[j+count_offset] == 0) {
                SIM_TIMERS[j+count_offset] = SIM_TIMERS[j+timeout_offset];
                SIM_TIMERS[j+overtime_offset] = 1;
            }
        }
    }
}

uint8_t sim_timer_check_running(uint8_t sim_timer_num)
{
    if(sim_timer_num < SIM_TIMER_MAX){
        sim_timer_num = sim_timer_num*4;
        return SIM_TIMERS[sim_timer_num+running_offset];
    }
    else{
        return 0;
    }
}

uint8_t sim_timer_check_overtime(uint8_t sim_timer_num)
{
    uint8_t ret;
    if(sim_timer_num < SIM_TIMER_MAX){
        sim_timer_num = sim_timer_num*4;
        ret =  SIM_TIMERS[sim_timer_num+overtime_offset];
        SIM_TIMERS[sim_timer_num+overtime_offset] = 0;
        return ret;
    }
    else{
        return 0;
    }
}

void sim_timer_start(uint8_t sim_timer_num)
{
    if(sim_timer_num < SIM_TIMER_MAX){
        sim_timer_num = sim_timer_num*4;
        SIM_TIMERS[sim_timer_num+running_offset] = 1;
    }  
}

void sim_timer_stop(uint8_t sim_timer_num)
{
    if(sim_timer_num < SIM_TIMER_MAX){
        sim_timer_num = sim_timer_num*4;
        SIM_TIMERS[sim_timer_num+running_offset] = 0;
    }  
}

void sim_timer_restart(uint8_t sim_timer_num)
{ 
    if(sim_timer_num < SIM_TIMER_MAX){
        sim_timer_num = sim_timer_num*4;
        SIM_TIMERS[sim_timer_num+count_offset] = SIM_TIMERS[sim_timer_num+timeout_offset];
        SIM_TIMERS[sim_timer_num+running_offset] = 1;
    }
}

void sim_timer_set_timeout(uint8_t sim_timer_num, uint16_t timeout)
{ 
    if(sim_timer_num < SIM_TIMER_MAX){
        sim_timer_num = sim_timer_num*4;
        SIM_TIMERS[sim_timer_num+timeout_offset] = timeout;
    }
}
